package com.tuhui.listener;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ListenerFile {

    public static ExecutorService fixedThreadPool = Executors.newCachedThreadPool();
    public WatchService watchService;
    private ListenerFile() {
        try {
            watchService = FileSystems.getDefault().newWatchService();
            start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void start() {
        fixedThreadPool.execute(new Listener(watchService));
    }

    public static void addListener(String path) throws Exception {
        ListenerFile resourceListener = new ListenerFile();
        List<String> pathList = (List<String>) getDirectorys(path);
        pathList.forEach(paths->{
            Path p = Paths.get(paths);
            //如果文件下面还有文件则都注册监听
            try {
                p.register(resourceListener.watchService,StandardWatchEventKinds.ENTRY_CREATE);
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("注册监听文件失败！");
            }
        });
        //第一次启动是否上传所有的文件
        if(FtpUtil.allUpload){
            List<File> fileList = getFiles(path);
            fileList.forEach(file -> {
                try {
                    FileInputStream in=new FileInputStream(file);
                    //ftp文件保持不变
                    String filePath[] = file.getParent().split("\\\\");
                    String ftpPath[] = FtpUtil.listenerPath.split("\\\\");
                    String uploadFtpPath =  FtpUtil.ftpPath;
                    if(filePath.length!=ftpPath.length){
                        for(int i=ftpPath.length;i<filePath.length;i++){
                            uploadFtpPath+="/"+filePath[i];
                        }
                    }
                   Boolean  upladStatus =  FtpUtil.uploadFile(FtpUtil.ftpHost, FtpUtil.ftpUserName, FtpUtil.ftpPassword, FtpUtil.ftpPort, uploadFtpPath, file.getName(),new FileInputStream(file));
                    //上传失败记录
                    if(!upladStatus){
                        FtpUtil.writFile(file.getPath());
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    System.out.println("upload fail");
                    FtpUtil.writFile(file.getPath());
                }
            });
        }
    }


    public static void main(String[] args) throws Exception {
       /* if(args==null || args.length<=0){
            System.out.println("请传递一个正确的properties文件配置的地址");
            Scanner scan = new Scanner(System.in);
            args = new String[]{scan.nextLine()};
        }
        System.out.println("读取文件的地址是："+args[0]);*/
        FtpUtil.setFtp();
        //启动定时任务
        Timer timer = new Timer();
        FileTimerTask fileTimerTask = new FileTimerTask();
        //程序运行后立刻执行任务，每隔100ms执行一次
        timer.schedule(fileTimerTask, 0, 10000*FtpUtil.timeMin);
    }


    /**
     * 获得文件下的所有文件
     * @param path
     * @return
     * @throws Exception
     */
    public static ArrayList<File> getFiles(String path) throws Exception {
        //目标集合fileList
        ArrayList<File> fileList = new ArrayList<File>();
        File file = new File(path);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File fileIndex : files) {
                //如果这个文件是目录，则进行递归搜索
                if (fileIndex.isDirectory()) {
                    fileList.addAll(getFiles(fileIndex.getPath()));
                } else {
                    //如果文件是普通文件，则将文件句柄放入集合中
                    fileList.add(fileIndex);

                }
            }
        }else{
            fileList.add(file);
        }
        return fileList;
    }

    /**
     * 获得文件下的所有目录
     * @param path
     * @return
     * @throws Exception
     */
    public static Collection<? extends String> getDirectorys(String path) throws Exception {
        //目标集合fileList
        ArrayList<String> fileList = new ArrayList<String>();
        File file = new File(path);
        if (file.isDirectory()) {
            fileList.add(path);
            File[] files = file.listFiles();
            for (File fileIndex : files) {
                //如果这个文件是目录，则进行递归搜索
                if (fileIndex.isDirectory()) {
                    fileList.addAll(getDirectorys(fileIndex.getPath()));
                }
            }
        }
        return fileList;
    }

}
